import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { DyneemaRopeSpecAPI } from '@/api/DyneemaRopeSpec';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Plus, Edit, Trash2, Save, X, MoreHorizontal, Cable, ChevronLeft, ChevronRight ,Search} from 'lucide-react';
import { useToast } from '@/components/ui/use-toast';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

// 表单组件保持不变
const DyneemaRopeSpecForm = ({ spec, onSubmit, onCancel }) => {
  const [formData, setFormData] = useState(spec ? {
    ...spec,
    nominalDiameter: spec.nominalDiameter ?? null,
    linearDensity: spec.linearDensity ?? null,
    effectiveCrossSectionalArea: spec.effectiveCrossSectionalArea ?? null,
    breakingForce: spec.breakingForce ?? null,
    resinCoatedDiameter: spec.resinCoatedDiameter ?? null,
    resinCoatedLinearDensity: spec.resinCoatedLinearDensity ?? null,
    sheathedDiameter: spec.sheathedDiameter ?? null,
    sheathedLinearDensity: spec.sheathedLinearDensity ?? null,
    materialDensity: spec.materialDensity ?? "",
    elasticModulus: spec.elasticModulus ?? "",
    fiberType: spec.fiberType ?? "",
    isActive: spec.isActive ?? true,
  } : {
    nominalDiameter: null,
    linearDensity: null,
    effectiveCrossSectionalArea: null,
    breakingForce: null,
    resinCoatedDiameter: null,
    resinCoatedLinearDensity: null,
    sheathedDiameter: null,
    sheathedLinearDensity: null,
    materialDensity: '',
    elasticModulus: '',
    fiberType:"",
    isActive: true,
  });

  const handleChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleNumberChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value === '' ? null : parseFloat(value) }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    onSubmit(formData);
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="w-full max-w-3xl max-h-[90vh] overflow-y-auto bg-white rounded-lg shadow-xl">
        <div className="p-6 border-b">
          <div className="flex justify-between items-center">
            <div className="flex items-center gap-2">
              <Cable className="w-5 h-5 text-blue-600" />
              {spec ? '编辑迪尼玛绳规格' : '新建迪尼玛绳规格'}
            </div>
            <Button variant="ghost" size="icon" onClick={onCancel}>
              <X className="w-4 h-4" />
            </Button>
          </div>
        </div>
        <div className="p-6">
          <form onSubmit={handleSubmit} className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label htmlFor="nominalDiameter">公称直径 (mm)*</Label>
                <Input 
                  id="nominalDiameter" 
                  type="number" 
                  step="0.1" 
                  value={formData.nominalDiameter ?? ''} 
                  onChange={e => handleNumberChange('nominalDiameter', e.target.value)} 
                  required 
                />
              </div>
              <div>
                <Label htmlFor="breakingForce">破断拉力 (kN)*</Label>
                <Input 
                  id="breakingForce" 
                  type="number" 
                  step="0.1" 
                  value={formData.breakingForce ?? ''} 
                  onChange={e => handleNumberChange('breakingForce', e.target.value)} 
                  required 
                />
              </div>
              <div>
                <Label htmlFor="linearDensity">线密度 (kg/m)*</Label>
                <Input 
                  id="linearDensity" 
                  type="number" 
                  step="0.00001" 
                  value={formData.linearDensity ?? ''} 
                  onChange={e => handleNumberChange('linearDensity', e.target.value)} 
                  required 
                />
              </div>
              <div>
                <Label htmlFor="effectiveCrossSectionalArea">有效截面积 S* (mm²)*</Label>
                <Input 
                  id="effectiveCrossSectionalArea" 
                  type="number" 
                  step="0.01" 
                  value={formData.effectiveCrossSectionalArea ?? ''} 
                  onChange={e => handleNumberChange('effectiveCrossSectionalArea', e.target.value)} 
                  required 
                />
              </div>
            </div>

            <div className="border-t pt-4">
              <h4 className="font-medium text-gray-900 mb-3">涂树脂后参数（可选）</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="resinCoatedDiameter">涂树脂后直径 (mm)</Label>
                  <Input 
                    id="resinCoatedDiameter" 
                    type="number" 
                    step="0.1" 
                    value={formData.resinCoatedDiameter ?? ''} 
                    onChange={e => handleNumberChange('resinCoatedDiameter', e.target.value)} 
                  />
                </div>
                <div>
                  <Label htmlFor="resinCoatedLinearDensity">涂树脂后线密度 (kg/m)</Label>
                  <Input 
                    id="resinCoatedLinearDensity" 
                    type="number" 
                    step="0.00001" 
                    value={formData.resinCoatedLinearDensity ?? ''} 
                    onChange={e => handleNumberChange('resinCoatedLinearDensity', e.target.value)} 
                  />
                </div>
              </div>
            </div>

            <div className="border-t pt-4">
              <h4 className="font-medium text-gray-900 mb-3">护套后参数（可选）</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="sheathedDiameter">护套后直径 (mm)</Label>
                  <Input 
                    id="sheathedDiameter" 
                    type="number" 
                    step="0.1" 
                    value={formData.sheathedDiameter ?? ''} 
                    onChange={e => handleNumberChange('sheathedDiameter', e.target.value)} 
                  />
                </div>
                <div>
                  <Label htmlFor="sheathedLinearDensity">护套后线密度 (kg/m)</Label>
                  <Input 
                    id="sheathedLinearDensity" 
                    type="number" 
                    step="0.00001" 
                    value={formData.sheathedLinearDensity ?? ''} 
                    onChange={e => handleNumberChange('sheathedLinearDensity', e.target.value)} 
                  />
                </div>
              </div>
            </div>

            <div className="border-t pt-4">
              <h4 className="font-medium text-gray-900 mb-3">材料特性</h4>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <Label htmlFor="materialDensity">材料比重 (g/cm³)</Label>
                  <Input 
                    id="materialDensity" 
                    type="number" 
                    step="0.01" 
                    value={formData.materialDensity ?? ''} 
                    onChange={e => handleNumberChange('materialDensity', e.target.value)} 
                  />
                </div>
                <div>
                  <Label htmlFor="elasticModulus">弹性模量 (N/mm²)</Label>
                  <Input 
                    id="elasticModulus" 
                    type="number" 
                    step="1" 
                    value={formData.elasticModulus ?? ''} 
                    onChange={e => handleNumberChange('elasticModulus', e.target.value)} 
                  />
                </div>
                <div>
                  <Label htmlFor="fiberType">纤维类型</Label>
                  <Input 
                    id="fiberType" 
                    value={formData.fiberType ?? ''} 
                    onChange={e => handleChange('fiberType', e.target.value)} 
                  />
                </div>
              </div>
            </div>

            <div className="flex justify-end gap-3 pt-4">
              <Button type="button" variant="outline" onClick={onCancel}>取消</Button>
              <Button type="submit">
                <Save className="w-4 h-4 mr-2" />
                保存
              </Button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default function DyneemaRopeSpecManager() {
  const [specs, setSpecs] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingSpec, setEditingSpec] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [searchTerm, setSearchTerm] = useState('');
  const { toast } = useToast();

  // 加载数据
  const loadSpecs = useCallback(async () => {
    setIsLoading(true);
    try {
      const res = await DyneemaRopeSpecAPI.getList();
      setSpecs(res.data);
    } catch (error) {
      toast({ variant: "destructive", title: "加载失败", description: "无法加载迪尼玛绳规格数据。" });
    }
    setIsLoading(false);
  }, [toast]);

  useEffect(() => {
    loadSpecs();
  }, [loadSpecs]);

  // 处理表单提交
  const handleSubmit = async (formData) => {
    try {
      if (editingSpec) {
        await DyneemaRopeSpecAPI.update(editingSpec.id, formData);
        toast({ title: "更新成功" });
      } else {
        await DyneemaRopeSpecAPI.create(formData);
        toast({ title: "创建成功" });
      }
      setShowForm(false);
      setEditingSpec(null);
      loadSpecs();
    } catch (error) {
      toast({ variant: "destructive", title: "操作失败", description: error.message });
    }
  };

  // 处理删除
  const handleDelete = async (id) => {
    if (window.confirm('确定要删除此规格吗？')) {
      try {
        await DyneemaRopeSpecAPI.delete(id);
        toast({ title: "删除成功" });
        loadSpecs();
      } catch (error) {
        toast({ variant: "destructive", title: "删除失败", description: error.message });
      }
    }
  };

  // 筛选数据
  const filteredSpecs = useMemo(() => {
    if (!searchTerm) return specs;
    
    const term = searchTerm.toLowerCase();
    return specs.filter(spec => 
      (spec.nominalDiameter?.toString().includes(term)) ||
      (spec.breakingForce?.toString().includes(term)) ||
      (spec.fiberType?.toLowerCase().includes(term)) ||
      (spec.materialDensity?.toString().includes(term))
    );
  }, [specs, searchTerm]);

  // 分页处理
  const totalItems = filteredSpecs.length;
  const totalPages = Math.ceil(totalItems / itemsPerPage);
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentSpecs = filteredSpecs.slice(indexOfFirstItem, indexOfLastItem);

  // 分页控制函数
  const handlePageChange = (pageNum) => {
    if (pageNum >= 1 && pageNum <= totalPages) {
      setCurrentPage(pageNum);
      window.scrollTo({ top: 0, behavior: "smooth" });
    }
  };

  const handleItemsPerPageChange = (count) => {
    setItemsPerPage(count);
    setCurrentPage(1);
  };

  // 渲染分页组件
  const renderPagination = () => (
    <div className="flex flex-col sm:flex-row items-center justify-between gap-4 px-4 py-3 border-t">
      <div className="text-sm text-gray-500">
        共 {totalItems} 条数据，显示
        {(currentPage - 1) * itemsPerPage + 1} 到
        {Math.min(currentPage * itemsPerPage, totalItems)} 条
      </div>
      <div className="flex items-center gap-2">
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" size="sm" className="h-8">
              每页 {itemsPerPage} 条
              <MoreHorizontal className="ml-2 h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            {[5, 10, 20, 50].map((count) => (
              <DropdownMenuItem
                key={count}
                onClick={() => handleItemsPerPageChange(count)}
              >
                {count} 条/页
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>
        <div className="flex items-center gap-1">
          <Button
            variant="outline"
            size="icon"
            className="h-8 w-8"
            onClick={() => handlePageChange(currentPage - 1)}
            disabled={currentPage === 1}
          >
            <ChevronLeft className="h-4 w-4" />
            <span className="sr-only">上一页</span>
          </Button>
          {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
            let pageNum;
            if (totalPages <= 5) {
              pageNum = i + 1;
            } else if (currentPage <= 3) {
              pageNum = i + 1;
            } else if (currentPage >= totalPages - 2) {
              pageNum = totalPages - 4 + i;
            } else {
              pageNum = currentPage - 2 + i;
            }
            return (
              <Button
                key={pageNum}
                variant={currentPage === pageNum ? "default" : "outline"}
                size="icon"
                className="h-8 w-8"
                onClick={() => handlePageChange(pageNum)}
              >
                {pageNum}
              </Button>
            );
          })}
          <Button
            variant="outline"
            size="icon"
            className="h-8 w-8"
            onClick={() => handlePageChange(currentPage + 1)}
            disabled={currentPage === totalPages}
          >
            <ChevronRight className="h-4 w-4" />
            <span className="sr-only">下一页</span>
          </Button>
        </div>
      </div>
    </div>
  );

  return (
    <div className="space-y-6">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <h3 className="text-xl font-bold flex items-center gap-2">
          <Cable className="w-5 h-5 text-blue-600" />
          迪尼玛绳规格库
        </h3>
        <div className="flex w-full md:w-auto gap-3">
          <div className="relative flex-1 md:flex-none md:w-64">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
            <Input
              placeholder="搜索直径、拉力或材料..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10"
            />
          </div>
          <Button onClick={() => { setEditingSpec(null); setShowForm(true); }}>
            <Plus className="w-4 h-4 mr-2" />
            新建规格
          </Button>
        </div>
      </div>

      {isLoading ? (
        <div className="text-center py-16 px-4 text-gray-500 border rounded-lg bg-gray-50 border-gray-200">
          加载中...
        </div>
      ) : totalItems > 0 ? (
        <div className="rounded-lg border border-gray-200 overflow-hidden shadow-sm">
          <div className="overflow-x-auto">
            <Table>
              <TableHeader className="bg-gray-50 border-b border-gray-200">
                <TableRow>
                  <TableHead className="w-[120px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    公称直径 (mm)
                  </TableHead>
                  <TableHead className="w-[120px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    破断拉力 (kN)
                  </TableHead>
                  <TableHead className="w-[120px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    线密度 (kg/m)
                  </TableHead>
                  <TableHead className="w-[140px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    有效截面积 (mm²)
                  </TableHead>
                  <TableHead className="w-[120px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    涂脂直径 (mm)
                  </TableHead>
                  <TableHead className="w-[120px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    护套直径 (mm)
                  </TableHead>
                  <TableHead className="w-[120px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    材料比重 (g/cm³)
                  </TableHead>
                  <TableHead className="w-[120px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    纤维类型
                  </TableHead>
                  <TableHead className="w-[80px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    状态
                  </TableHead>
                  <TableHead className="w-[100px] py-3 px-4 text-right text-sm font-semibold text-gray-700">
                    操作
                  </TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {currentSpecs.map((spec) => (
                  <TableRow
                    key={spec.id}
                    className="transition-colors duration-150 border-b border-gray-100 last:border-0 hover:bg-gray-50"
                  >
                    <TableCell className="py-3 px-4 text-gray-800 text-sm font-mono">
                      {spec.nominalDiameter ?? '-'}
                    </TableCell>
                    <TableCell className="py-3 px-4 text-gray-800 text-sm font-mono">
                      {spec.breakingForce ?? '-'}
                    </TableCell>
                    <TableCell className="py-3 px-4 text-gray-800 text-sm font-mono">
                      {spec.linearDensity ?? '-'}
                    </TableCell>
                    <TableCell className="py-3 px-4 text-gray-800 text-sm font-mono">
                      {spec.effectiveCrossSectionalArea ?? '-'}
                    </TableCell>
                    <TableCell className="py-3 px-4 text-gray-800 text-sm font-mono">
                      {spec.resinCoatedDiameter ?? '-'}
                    </TableCell>
                    <TableCell className="py-3 px-4 text-gray-800 text-sm font-mono">
                      {spec.sheathedDiameter ?? '-'}
                    </TableCell>
                    <TableCell className="py-3 px-4 text-gray-800 text-sm font-mono">
                      {spec.materialDensity ?? '-'}
                    </TableCell>
                    <TableCell className="py-3 px-4 text-gray-800 text-sm">
                      {spec.fiberType || '-'}
                    </TableCell>
                    <TableCell className="py-3 px-4">
                      {spec.isActive ? (
                        <Badge className="bg-green-100 text-green-700">可用</Badge>
                      ) : (
                        <Badge className="bg-gray-100 text-gray-700">禁用</Badge>
                      )}
                    </TableCell>
                    <TableCell className="py-3 px-4 text-right">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-8 w-8 text-gray-600 hover:text-blue-600 hover:bg-blue-50 transition-colors"
                          >
                            <MoreHorizontal className="w-4 h-4" />
                            <span className="sr-only">操作菜单</span>
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end" className="w-[140px]">
                          <DropdownMenuItem onClick={() => {
                            setEditingSpec(spec);
                            setShowForm(true);
                          }}>
                            <Edit className="w-4 h-4 mr-2" />
                            编辑
                          </DropdownMenuItem>
                          <DropdownMenuSeparator />
                          <DropdownMenuItem
                            onClick={() => handleDelete(spec.id)}
                            className="text-red-600"
                          >
                            <Trash2 className="w-4 h-4 mr-2" />
                            删除
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
          {renderPagination()}
        </div>
      ) : (
        <div className="text-center py-12 text-gray-500 bg-white rounded-lg shadow-sm border border-gray-200">
          <Cable className="w-12 h-12 mx-auto mb-4 text-gray-300" />
          <p className="text-lg font-medium mb-2">暂无迪尼玛绳规格数据</p>
          <Button variant="link" onClick={() => { 
            setEditingSpec(null); 
            setShowForm(true); 
          }}>
            点击创建第一条规格
          </Button>
        </div>
      )}

      {showForm && (
        <DyneemaRopeSpecForm
          spec={editingSpec}
          onSubmit={handleSubmit}
          onCancel={() => {
            setShowForm(false);
            setEditingSpec(null);
          }}
        />
      )}
    </div>
  );
}

 